package com.quanyan.authority.web;

import com.alibaba.fastjson.JSONObject;
import com.lefu.commons.utils.Page;
import com.lefu.commons.utils.lang.JsonUtils;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.authority.model.db.TbRole;
import com.quanyan.authority.model.db.TbRoleMenu;
import com.quanyan.authority.model.request.ReqRole;
import com.quanyan.authority.service.RoleMenuService;
import com.quanyan.authority.service.RoleService;
import com.quanyan.common.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import scala.util.parsing.combinator.testing.Str;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/4.
 */
@RestController
@RequestMapping("/admin/api/authority/role/api/")
public class RoleController extends BaseController<ReqRole> {
    private static final Logger logger = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private HttpServletRequest request;

    @Override
    @RequestMapping(value = "save",method = RequestMethod.POST)
    public APIResponse save(@RequestBody @Valid ReqRole reqRole, BindingResult bindingResult) {
         if(bindingResult.hasErrors())
             return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        try {
            int uid = (Integer.parseInt(request.getAttribute("adminUid").toString()));
            reqRole.setFounder(uid);
            TbRole t = roleService.add(reqRole);

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "query",method = RequestMethod.POST)
    public APIResponse query(@RequestBody ReqRole reqRole) {
        try {
            Page page = roleService.findAll(reqRole, reqRole);
            return APIResponse.returnSuccess(page);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "queryById",method = RequestMethod.POST)
    public APIResponse queryById(@RequestBody Map map) {
        try {
            Integer id = (Integer.parseInt( map.get("id").toString()));
            if(id == null)
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);

            Map<String,Object> m = new HashMap<>();
            m.put("respRole",roleService.findById(id));
            m.put("respMenuIds",roleMenuService.getMenuId(id));
            return APIResponse.returnSuccess(m);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public APIResponse update(@RequestBody ReqRole reqRole) {
        try {
            roleService.update(reqRole);
            List<TbRoleMenu> idsDel = reqRole.getIdsDel();
            List<TbRoleMenu> idsAdd = reqRole.getIdsAdd();
            if(idsDel != null && idsDel.size() > 0)
                roleMenuService.batchDelRoleMenu(idsDel);

            if(idsAdd != null && idsAdd.size() > 0 )
                roleMenuService.batchAddRoleMenu(idsAdd);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @RequestMapping(value = "update1",method = RequestMethod.POST)
    public APIResponse updateDe(@RequestBody Map map) {
        try {
            String objStr = map.get("reqRole").toString();
            //ReqRole reqRole = JSONObject.parseObject(objStr, ReqRole.class);
            ReqRole reqRole = GsonUtils.jsonStrToEntity(objStr,ReqRole.class);
            List<TbRoleMenu> idsAdd  =(List<TbRoleMenu>)map.get("idsAdd");
            List<TbRoleMenu> idsDel  =(List<TbRoleMenu>)map.get("idsDel");

            roleService.update(reqRole);
            if(idsDel.isEmpty() && idsDel.size() > 0)
                roleMenuService.batchDelRoleMenu(idsDel);

            if(idsAdd.isEmpty() && idsAdd.size() > 0 )
                roleMenuService.batchAddRoleMenu(idsAdd);

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public APIResponse deleteById(@RequestBody Map map) {
        try {
            Integer id = (Integer.parseInt( map.get("id").toString()));
            if(id == null)
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
            roleService.del(id);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }
}
